package cn.demoxy.service.impl;

import cn.demoxy.mapper.DemoRoleMapper;
import cn.demoxy.mapper.DemoRoleMenuMapper;
import cn.demoxy.mapper.DemoUserRoleMapper;
import cn.demoxy.model.dto.DemoRoleDTO;
import cn.demoxy.model.entity.DemoLog;
import cn.demoxy.model.entity.DemoRole;
import cn.demoxy.model.entity.DemoRoleMenu;
import cn.demoxy.model.entity.DemoUserRole;
import cn.demoxy.service.IDemoRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther demo
 * @date 2022/5/18 20:53
 * 角色表业务实现
 */
@Service
@AllArgsConstructor
public class DemoRoleServiceImpl extends ServiceImpl<DemoRoleMapper, DemoRole> implements IDemoRoleService {

    private DemoRoleMenuMapper roleMenuMapper;

    private DemoUserRoleMapper userRoleMapper;
    @Override
    public IPage<DemoRole> findAllRoleByKeyword(DemoRoleDTO roleDTO) {
        //创建page对象，传递当前页，每页记录数
        Page<DemoRole> page = new Page<>(roleDTO.getCurrent(), roleDTO.getSize());
        //构建条件
        QueryWrapper<DemoRole> wrapper = new QueryWrapper<>();
        //根据角色名称查询
        if (StringUtils.hasText(roleDTO.getRoleName())) {
            wrapper.like("role_name", roleDTO.getRoleName());
        }
        //调用方法实现分页查询
        Page<DemoRole> rolePages = baseMapper.selectPage(page,wrapper);
        //返回结果
        return rolePages;
    }

    @Override
    public boolean addPermission(DemoRoleDTO roleDTO) {
        List<DemoRoleMenu> roleMenus = roleMenuMapper.selectList(new QueryWrapper<DemoRoleMenu>().eq("role_id", roleDTO.getRoleId()));
        //该角色已经绑定过权限为更新先删除之前绑定的权限
        if (roleMenus.size()>0){
            roleMenuMapper.delete(new QueryWrapper<DemoRoleMenu>().eq("role_id", roleDTO.getRoleId()));
        }
        for (String menuId : roleDTO.getMenuIds()) {
            roleMenuMapper.insert(new DemoRoleMenu().setRoleId(roleDTO.getRoleId()).setMenuId(menuId));
        }
        return true;
    }

    @Override
    public List<String> findMenuByRoleId(String roleId) {
        List<String> menuIds = new ArrayList<>();
        List<DemoRoleMenu> roleMenus = roleMenuMapper.selectList(new QueryWrapper<DemoRoleMenu>().eq("role_id", roleId));
        roleMenus.forEach(roleMenu->{
            menuIds.add(roleMenu.getMenuId());
        });
        return menuIds;
    }

    @Override
    public boolean deleteRole(String id) {
        try {
            userRoleMapper.delete(new QueryWrapper<DemoUserRole>().eq("role_id",id));
            baseMapper.deleteById(id);
        }catch (Exception e){
            return false;
        }

        return true;
    }
}
